package com.gjs.common.manager;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

public class SecurityOauthUtil {

    private TokenStore tokenStore;

    public SecurityOauthUtil(TokenStore tokenStore){
        this.tokenStore = tokenStore;
    }

    public String getUserSnByJwt(){
        String userSn = (String) getAdditionalInformation().get("user_sn");
        Assert.notNull(userSn,"尚未登录或缺少用户唯一序列号");
        return userSn;
    }

    private Map<String,Object> getAdditionalInformation(){
        Map<String,Object> additionalInformation = new HashMap<>();
        Object detailsObj =  SecurityContextHolder.getContext().getAuthentication().getDetails();
        if(detailsObj instanceof OAuth2AuthenticationDetails){
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) detailsObj;
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
            additionalInformation = accessToken.getAdditionalInformation();
        }
        return additionalInformation;
    }
}
